<template>
  <el-dialog
    :title="title"
    :visible.sync="openSheet"
    width="600px"
    :destroy-on-close="true"
    :close-on-click-modal="false"
    :before-close="cancel"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <el-row>
        <el-col :span="24">
          <el-form-item :label="$t('calendarType')" prop="calendar_type" :error="error.calendar_type">
            <el-input
              v-model="form.calendar_type"
              :disabled="!createFlag"
              maxlength="1"
              :placeholder="$t('inputCalendarType')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('calendarName')" prop="calendar_name" :error="error.calendar_name">
            <el-input
              v-model="form.calendar_name"
              maxlength="50"
              show-word-limit
              :placeholder="$t('inputCalendarName')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('calendarHoliday')">
            <el-checkbox-group v-model="form.holiday" size="small">
              <el-checkbox-button v-for="day in days" :key="day.value" :label="day.value">{{ day.label }}</el-checkbox-button>
            </el-checkbox-group>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button v-if="createFlag" type="primary" :disabled="!isModified" @click="submitForm">{{
        $t('create')
      }}</el-button>
      <el-button v-else type="primary" :disabled="!isModified" @click="submitForm">{{
        $t('update')
      }}</el-button>
      <el-button @click="cancel">{{ $t('cancel') }}</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { createCalendarTypeApi, updateCalendarTypeApi } from '../api/calendars.api'
export default {
  data() {
    return {
      createFlag: true,
      title: undefined,
      id: undefined,
      openSheet: false,
      form: {
        calendar_type: undefined,
        calendar_name: undefined,
        holiday: undefined
      },
      error: {
        calendar_type: undefined,
        calendar_name: undefined,
        holiday: undefined
      }
    };
  },
  computed: {
    isModified() {
      // 判断表单数据是否有变化
      return JSON.stringify(this.form) !== JSON.stringify(this.originalForm);
    },
    days() {
      return [
        { label: this.$t('monday'), value: '1' },
        { label: this.$t('tuesday'), value: '2' },
        { label: this.$t('wednesday'), value: '3' },
        { label: this.$t('thursday'), value: '4' },
        { label: this.$t('friday'), value: '5' },
        { label: this.$t('saturday'), value: '6' },
        { label: this.$t('sunday'), value: '7' }
      ]
    },
    rules() {
      return {
        calendar_type: [
          {
            required: true,
            message: this.$t('calendarTypeRequire'),
            trigger: 'blur'
          }
        ],
        calendar_name: [
          {
            required: true,
            message: this.$t('calendarNameRequire'),
            trigger: 'blur'
          }
        ]
      }
    }
  },
  methods: {
    /** 打开Dialog 画面 */
    openSheetDialog(data) {
      this.openSheet = !this.openSheet;
      this.reset();
      if (data) {
        this.title = this.$t('calendarTypeCreateTitle')
        this.createFlag = false
        this.id = data.id
        this.form.calendar_name = data.calendar_name
        this.form.calendar_type = data.calendar_type
        this.form.holiday = this.filterArrayBasedOnIndicator(data.holiday)
      } else {
        this.title = this.$t('calendarTypeCreateTitle')
        this.createFlag = true
        this.id = undefined
      }
      this.originalForm = {
        ...this.form
      }
    },
    cancel() {
      this.openSheet = !this.openSheet
    },
    reset() {
      this.resetForm('form')
      this.resetJsonObject(this.form)
      this.form.holiday = []
      this.resetJsonObject(this.error)
    },
    submitForm: function() {
      this.$refs['form'].validate(async valid => {
        if (valid) {
          this.resetJsonObject(this.error)
          var data = { ...this.form }
          data.holiday = this.createStringBasedOnArray(data.holiday.sort())
          var resp;
          if (this.createFlag) {
            resp = await createCalendarTypeApi(data);
          } else {
            resp = await updateCalendarTypeApi(this.id, data);
          }
          if (resp.success) {
            this.$emit('refreshList');
            this.openSheet = !this.openSheet
            if (this.createFlag) {
              this.targaMessage(
                this.$t('createSuccess', {
                  title: this.$t('calendarType'),
                  value: this.form.calendar_type
                })
              );
            } else {
              this.targaMessage(
                this.$t('updateSuccess', {
                  title: this.$t('calendarType'),
                  value: this.form.calendar_type
                })
              );
            }
          } else {
            if (typeof resp.msg === 'object') {
              this.error = resp.msg
            } else {
              this.targaMessageBox(this, resp.msg)
            }
          }
        }
      });
    },
    createStringBasedOnArray(inputArray) {
      // 定义一个数组，包含1到7的字符串表示
      const numbers = ['1', '2', '3', '4', '5', '6', '7'];
      // 初始化结果字符串
      let resultString = '';

      // 遍历1到7的数组
      for (let i = 0; i < numbers.length; i++) {
        // 检查当前数字是否在输入数组中
        if (inputArray.includes(numbers[i])) {
          resultString += 'Y';
        } else {
          resultString += 'N';
        }
      }
      return resultString;
    },
    filterArrayBasedOnIndicator(indicatorString) {
      const resultArray = [];
      const existingArray = ['1', '2', '3', '4', '5', '6', '7'];

      // 遍历字符串和数组
      for (let i = 0; i < indicatorString.length; i++) {
        // 如果当前字符是 'Y' 并且对应的数字存在于 existingArray 中
        if (indicatorString[i] === 'Y') {
          const number = i + 1; // 将索引转换为数字
          // 只添加 existingArray 中存在的数字
          if (existingArray.includes(number.toString())) {
            resultArray.push(number.toString());
          }
        }
        // 如果字符是 'N'，不进行任何操作
      }

      return resultArray;
    }
  }
};
</script>
